package org.sixtythousand.joker.servlet;

import org.sixtythousand.joker.Request;
import org.sixtythousand.joker.Response;
import org.sixtythousand.joker.http.HttpHandler;
import org.sixtythousand.joker.servlet.servlet.DefaultServlet;
import org.sixtythousand.joker.servlet.servlet.ServletWrapper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhoulk
 * @date 2023/10/18 17:36
 * @desc
 */
public abstract class AbstractServletContainer extends HttpHandler implements ServletContainer {

    protected List<ServletMapping> servletMappings;


    @Override
    public void dispatcher(Request request, Response response, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        servletMappings.stream().filter(mapping -> mapping.isMatch(httpServletRequest)).map(ServletMapping::getServlet).forEach(servlet -> {
            try {
                servlet.service(httpServletRequest, httpServletResponse);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public void doStart() {
        servletMappings = new ArrayList<>();
        ServletMapping defaultMapping = new ServletMapping("/404", new ServletWrapper(new DefaultServlet()));
    }


}
